<template>
    <div class="login-container">
        <div class="login-box">
            <div class="login-header">
                <img src="@/assets/img/logo.png" alt="logo" class="logo"/>
                <h2>欢迎登录</h2>
            </div>
            
            <div class="login-type">
                <el-radio-group v-model="loginType">
                    <el-radio-button label="account">账号登录</el-radio-button>
                    <el-radio-button label="email">邮箱登录</el-radio-button>
                </el-radio-group>
            </div>
            
            <el-form 
                ref="loginFormRef"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
            >
                <template v-if="loginType === 'account'">
                    <el-form-item prop="username">
                        <el-input 
                            v-model="loginForm.username"
                            placeholder="请输入用户名"
                            prefix-icon="User"
                        />
                    </el-form-item>
                    
                    <el-form-item prop="password">
                        <el-input 
                            v-model="loginForm.password"
                            type="password"
                            placeholder="请输入密码"
                            prefix-icon="Lock"
                            show-password
                        />
                    </el-form-item>
                </template>

                <template v-if="loginType === 'email'">
                    <el-form-item prop="email">
                        <el-input 
                            v-model="loginForm.email"
                            placeholder="请输入邮箱"
                            prefix-icon="Message"
                        />
                    </el-form-item>
                    
                    <el-form-item prop="emailCode">
                        <div class="verify-code-container">
                            <el-input 
                                v-model="loginForm.emailCode"
                                placeholder="请输入验证码"
                                prefix-icon="Key"
                            />
                            <el-button 
                                type="primary" 
                                :disabled="isCountingDown"
                                @click="sendEmailCodes"
                            >
                                {{ countDownText }}
                            </el-button>
                        </div>
                    </el-form-item>
                </template>
                
                <el-form-item prop="captcha">
                    <div class="captcha-container">
                        <Vcode :show="isShow" @success="success" @close="close" />
                    </div>
                </el-form-item>
                <div style="margin-left: 320px;margin-bottom: 10px;cursor: pointer;"
                    @click="$router.push('/user/findPassword')"
                >忘记密码？</div>
                <el-form-item>
                    <el-button 
                        type="primary" 
                        class="login-button"
                        :loading="loading"
                        @click="handleLogin"
                    >登录</el-button>
                </el-form-item>

                <div class="register-link">
                    还没有账号？<el-link type="primary" @click="goToRegister">立即注册</el-link>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Key, Message } from '@element-plus/icons-vue'
import { login, loginByEmail, sendEmailCode } from '@/api/user/user'
import Vcode from "vue3-puzzle-vcode";

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)
const captchaUrl = ref('')
const isShow = ref(false)
const isVerified = ref(false)
const loginType = ref('account')
const isCountingDown = ref(false)
const countDown = ref(0)
const countDownText = ref('发送验证码')

const loginForm = ref({
    username: '',
    password: '',
    email: '',
    emailCode: ''
})

watch(loginType, () => {
    loginForm.value = {
        username: '',
        password: '',
        email: '',
        emailCode: ''
    }
    if (loginFormRef.value) {
        loginFormRef.value.clearValidate()
    }
})

const loginRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    emailCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码长度为 6 位', trigger: 'blur' }
    ]
}

const success = () => {
  isShow.value = false
  isVerified.value = true
  handleLoginSubmit()
}

const close = () => {
  isShow.value = false
  isVerified.value = false
}

const handleLogin = async () => {
    if (!loginFormRef.value) return
    
    await loginFormRef.value.validate(async (valid) => {
        if (valid) {
            isShow.value = true
        } else {
            return false
        }
    })
}

const sendEmailCodes = async () => {
    try {
        await loginFormRef.value.validateField('email')
        if (!loginForm.value.email) {
            ElMessage.warning('请输入邮箱地址')
            return
        }
        
        isCountingDown.value = true
        countDown.value = 60
        countDownText.value = `${countDown.value}s`
        
        const res = await sendEmailCode(loginForm.value.email)
        if (res.code === 200) {
            ElMessage.success('验证码已发送，请查收邮件')
            
            const timer = setInterval(() => {
                countDown.value--
                countDownText.value = `${countDown.value}s`
                if (countDown.value <= 0) {
                    clearInterval(timer)
                    isCountingDown.value = false
                    countDownText.value = '发送验证码'
                }
            }, 1000)
        } else {
            isCountingDown.value = false
            countDown.value = 0
            countDownText.value = '发送验证码'
            throw new Error(res.message || '发送失败')
        }
    } catch (error) {
        isCountingDown.value = false
        countDown.value = 0
        countDownText.value = '发送验证码'
        console.error('发送验证码失败：', error)
        ElMessage.error(error.message || '发送验证码失败')
    }
}

const handleLoginSubmit = async () => {
    if (!loginFormRef.value) return
    
    await loginFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                loading.value = true
                
                const res = loginType.value === 'account'
                    ? await login({
                        username: loginForm.value.username,
                        password: loginForm.value.password,
                    })
                    : await loginByEmail({
                        email: loginForm.value.email,
                        code: loginForm.value.emailCode
                    })
                
                if (res.code === 200) {
                    ElMessage.success('登录成功')
                    localStorage.setItem('token', res.data.token)
                    localStorage.setItem('userInfo', JSON.stringify(res.data))
                    router.push('/user/home')
                } else {
                    ElMessage.error(res.message || '登录失败')
                    isVerified.value = false
                }
            } catch (error) {
                console.error('登录失败：', error)
                ElMessage.error('登录失败：' + error.message)
                isVerified.value = false
            } finally {
                loading.value = false
            }
        }
    })
}

const goToRegister = () => {
    router.push('/user/register')
}

onMounted(() => {
   
})

onBeforeUnmount(() => {
    if (captchaUrl.value) {
        URL.revokeObjectURL(captchaUrl.value)
    }
})
</script>

<style scoped>
.login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #1c92d2, #f2fcfe);
}

.login-box {
    width: 400px;
    padding: 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
    text-align: center;
    margin-bottom: 30px;
}

.logo {
    width: 80px;
    margin-bottom: 16px;
}

.login-header h2 {
    font-size: 24px;
    color: #303133;
    margin: 0;
}

.login-form {
    margin-top: 30px;
}

.captcha-container {
    display: flex;
    gap: 12px;
}

.captcha-img {
    height: 40px;
    cursor: pointer;
}

.remember-me {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.login-button {
    width: 100%;
    padding: 12px 0;
}

.register-link {
    text-align: center;
    margin-top: 16px;
    color: #606266;
}

:deep(.el-input__wrapper) {
    padding: 1px 11px;
}

:deep(.el-input__inner) {
    height: 40px;
}

.login-type {
    text-align: center;
    margin-bottom: 20px;
}

.verify-code-container {
    display: flex;
    gap: 12px;
}

.verify-code-container .el-button {
    width: 120px;
}
</style>